/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.ad.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.jeesite.autoconfigure.sys.FileAutoConfiguration;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mybatis.mapper.query.QueryType;
import com.jeesite.common.service.CrudService;
import com.jeesite.common.shiro.cas.CasOutHandler;
import com.jeesite.common.utils.AES;
import com.jeesite.common.utils.Base64;
import com.jeesite.modules.ad.dao.AdGuestDao;
import com.jeesite.modules.ad.entity.Ad;
import com.jeesite.modules.ad.entity.AdAgent;
import com.jeesite.modules.ad.entity.AdGuest;
import com.jeesite.modules.ad.entity.AdVertiser;
import com.jeesite.modules.ad.utils.api.utils.entity.JsonResult;
import com.jeesite.modules.ad.utils.api.utils.enums.JsonResultCodeEnum;
import com.jeesite.modules.file.entity.FileUpload;
import com.jeesite.modules.file.utils.FileUploadUtils;
import com.jeesite.modules.sys.utils.DictUtils;
import com.mchange.v1.util.CollectionUtils;
import com.twelvemonkeys.util.CollectionUtil;

/**
 * 广告获客Service
 * 
 * @author Liu,Wenzhao
 * @version 2019-04-17
 */
@Service
@Transactional(readOnly = true)
public class AdGuestService extends CrudService<AdGuestDao, AdGuest> {

	@Autowired
	private AdVertiserService adVertiserService;

	@Autowired
	private AdAgentService adAgentService;

	@Autowired
	private AdService adService;

	private static final String KRY = "000000000000000wwwbeihancloudcom";

	/** 返回结果实体 */
	private static JsonResult jsonResult = null;

	/**
	 * 获取单条数据
	 * 
	 * @param adGuest
	 * @return
	 */
	@Override
	public AdGuest get(AdGuest adGuest) {
		return super.get(adGuest);
	}

	/**
	 * 查询分页数据
	 * 
	 * @param adGuest 查询条件
	 * @param         adGuest.page 分页对象
	 * @return
	 */
	@Override
	public Page<AdGuest> findPage(AdGuest adGuest) {
		// 查询当前广告主
		AdVertiser v = this.adVertiserService.getCurVertiser();
		if (v == null) {
			v = new AdVertiser();
			// 查询当前代理商的广告主的客户
			AdAgent agent = this.adAgentService.getCurAgent();
			if (agent != null) {
				v.setAgentId(agent.getId());
				v.setAccount(adGuest.getAdVertiser().getAccount());
			}
		}
		adGuest.setAdVertiser(v);
		adGuest.getSqlMap().put("dsf", " 1=1");
		Page<AdGuest> page = super.findPage(adGuest);
		List<AdGuest> list = page.getList();
		if (!ListUtils.isEmpty(list)) {
			for (AdGuest g : list) {
				List<FileUpload> uList = FileUploadUtils.findFileUpload(g.getId(), "adGuest_audio");
				if (ListUtils.isEmpty(uList)) {
					continue;
				}
				FileUpload a = uList.get(0);
				g.setAudioUploadId(a.getId());
			}
		}
		return page;
	}

	/**
	 * 查询广告对应的获客数量
	 */
	public Integer findNumByAd(AdGuest adGuest) {
		adGuest.getSqlMap().getWhere().and("ad_id", QueryType.GTE, adGuest.getAd().getId());
		List list = super.findList(adGuest);
		return list.size();
	}

	/**
	 * 保存数据（插入或更新）
	 * 
	 * @param adGuest
	 */
	@Override
	@Transactional(readOnly = false)
	public void save(AdGuest adGuest) {
		super.save(adGuest);
		// 保存上传附件
		FileUploadUtils.saveFileUpload(adGuest.getId(), "adGuest_audio");
	}

	/**
	 * 更新状态
	 * 
	 * @param adGuest
	 */
	@Override
	@Transactional(readOnly = false)
	public void updateStatus(AdGuest adGuest) {
		super.updateStatus(adGuest);
	}

	/**
	 * 删除数据
	 * 
	 * @param adGuest
	 */
	@Override
	@Transactional(readOnly = false)
	public void delete(AdGuest adGuest) {
		super.delete(adGuest);
	}

	/**
	 * 解密验证
	 * 
	 * @param request 请求
	 * @return
	 */
	public static JsonResult decodeValidate(HttpServletRequest request) {
		// 获取签名秘钥
		String sha1hex = KRY.substring(16);
		// 获取解密秘钥
		String aeskey = KRY.substring(0, 16);
		// 获取签名报文
		String signature = request.getParameter("signData");
		// 获取加密报文
		String encryptData = request.getParameter("encryptData");
		if (signature == null || "".equals(signature)) {
			jsonResult = new JsonResult(JsonResultCodeEnum.ERROR_VALIDATE_NULL.getCode(),
					JsonResultCodeEnum.ERROR_VALIDATE_NULL.getMsg() + "<br/>signData", null);
			return jsonResult;
		}
		if (encryptData == null || "".equals(encryptData)) {
			jsonResult = new JsonResult(JsonResultCodeEnum.ERROR_VALIDATE_NULL.getCode(),
					JsonResultCodeEnum.ERROR_VALIDATE_NULL.getMsg() + "<br/>encryptData", null);
			return jsonResult;
		}
		// 获取请求参数内容
		String res = AES.decode(Base64.decode(encryptData), aeskey);
		// 验证签名(true为相同，false为不同)
		boolean signChecked = Objects.equals(signature.toUpperCase(), DigestUtils.sha1Hex(res + sha1hex).toUpperCase());
		if (signChecked) {
			Map<String, Object> map = new HashMap<String, Object>(1);
			map.put("DATA", res);
			jsonResult = new JsonResult(JsonResultCodeEnum.SUCCESS.getCode(), JsonResultCodeEnum.SUCCESS.getMsg(), map);
		} else {
			jsonResult = new JsonResult(JsonResultCodeEnum.REQUEST_SIGN_ERROR.getCode(),
					JsonResultCodeEnum.REQUEST_SIGN_ERROR.getMsg(), null);
		}
		return jsonResult;
	}

	/**
	 * 广告主信息查询接口(业务层)
	 * 
	 * @param request 请求
	 * @return 结果
	 */
	@Transactional(readOnly = false)
	public JsonResult T1001(HttpServletRequest request) {
		// 获取解密验证结果
		jsonResult = decodeValidate(request);
		// 成功
		if (JsonResultCodeEnum.SUCCESS.getCode() == jsonResult.getStatus()) {
			Map<String, Object> data = jsonResult.getData();
			// 获取解密后参数内容文本
			String requestMapText = (String) data.get("DATA");
			// 获取参数内容
			JSONObject jsonObject = JSONObject.parseObject(requestMapText);
			// 广告主账户名称
			String adVertisersAccount = jsonObject.getString("adVertisersAccount");
			// 设置查询条件
			AdVertiser adVertiserwhere = new AdVertiser();
			if (StringUtils.isBlank(adVertisersAccount)) {
				return jsonResult = new JsonResult(JsonResultCodeEnum.ERROR_VALIDATE_NULL.getCode(),
						JsonResultCodeEnum.ERROR_VALIDATE_NULL.getMsg() + "<br/>广告主账号名称", null);
			} else {
				adVertiserwhere.setAccount(adVertisersAccount);
			}
			List<AdVertiser> findList = adVertiserService.findList(adVertiserwhere);
			// 查询该广告主下的所有广告计划
			for (AdVertiser adVertiser : findList) {
				Ad adWhere = new Ad();
				adWhere.setVertiserId(adVertiser.getId());
				adVertiser.setAdList(adService.findList(adWhere));
			}
			// 封装返回结果
			List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>(1);
			for (AdVertiser adVertiser : findList) {
				Map<String, Object> adVertiserResultMap = new HashMap<String, Object>(8);
				// 广告主信息
				adVertiserResultMap.put("adVertiserID", adVertiser.getId());
				adVertiserResultMap.put("adVertisersAccount", adVertiser.getAccount());
				List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(16);
				List<Ad> adList = adVertiser.getAdList();
				for (Ad ad : adList) {
					Map<String, Object> adResultMap = new HashMap<String, Object>(8);
					adResultMap.put("adID", ad.getId());
					adResultMap.put("adVertisingProgrammeName", ad.getName());
					adResultMap.put("terminal",
							DictUtils.getDictLabel("ad_terminal", ad.getTerminal(), null) == null ? ad.getTerminal()
									: DictUtils.getDictLabel("ad_terminal", ad.getTerminal(), null));
					adResultMap.put("ADTypes",
							DictUtils.getDictLabel("ad_type", ad.getType(), null) == null ? ad.getType()
									: DictUtils.getDictLabel("ad_type", ad.getType(), null));
					adResultMap.put("deliveryStartTime", ad.getDeliveryStartTime());
					adResultMap.put("deliveryEndTime", ad.getDeliveryEndTime());
					adResultMap.put("deliveryRegional", ad.getAreaCode().getTreeNames());
					adResultMap.put("landingPageURL", ad.getUrl());
					list.add(adResultMap);
				}
				adVertiserResultMap.put("adList", list);
				resultList.add(adVertiserResultMap);
			}
			Map<String, Object> result = new HashMap<String, Object>(16);
			result.put("adVertiserList", resultList);
			jsonResult = new JsonResult(JsonResultCodeEnum.SUCCESS.getCode(), JsonResultCodeEnum.SUCCESS.getMsg(),
					result);
		}
		return jsonResult;
	}

	/**
	 * 获客信息新增接口(业务层)
	 * 
	 * @param request 请求
	 * @return 结果
	 */
	@Transactional(readOnly = false)
	public JsonResult T1002(HttpServletRequest request) {
		// 获取解密验证结果
		jsonResult = decodeValidate(request);
		// 成功
		if (JsonResultCodeEnum.SUCCESS.getCode() == jsonResult.getStatus()) {
			Map<String, Object> data = jsonResult.getData();
			// 获取解密后参数内容文本
			String requestMapText = (String) data.get("DATA");
			// 获取参数内容
			JSONObject jsonObject = JSONObject.parseObject(requestMapText);
			// 获取参数验证结果
			jsonResult = T1002Validate(jsonObject);
			// 成功
			if (JsonResultCodeEnum.SUCCESS.getCode() == jsonResult.getStatus()) {
				AdGuest insert = (AdGuest) jsonResult.getData().get("insert");
				// 新增获客信息
				try {
					insert(insert);
					// 返回接口调用结果
					jsonResult = new JsonResult(JsonResultCodeEnum.SUCCESS.getCode(),
							JsonResultCodeEnum.SUCCESS.getMsg(), null);
				} catch (Exception e) {
					e.printStackTrace();
					// 返回接口调用结果
					jsonResult = new JsonResult(JsonResultCodeEnum.SZF_SYS_ERROR.getCode(),
							JsonResultCodeEnum.SZF_SYS_ERROR.getMsg() + "<br/>" + e.getMessage(), null);
				}
			}
		}
		return jsonResult;
	}

	/**
	 * 
	 * 获客新增参数验证
	 * 
	 * @param jsonObject                 参数内容<br/>
	 *                                   ----------------------------
	 * @param phone                      手机号码
	 * @param phoneLocation              归属地
	 * @param sex                        性别（男 ,女）
	 * @param age                        年龄
	 * @param career                     职业
	 * @param guestTime                  获客时间
	 * @param media                      投放媒体
	 * @param mediaUrl                   来源媒体广告位媒体页URL
	 * @param advertisingPositionID      来源媒体广告位ID
	 * @param landingPageURL             落地页URL
	 * @param stayTime                   停留时间（秒）
	 * @param message                    留言内容
	 * @param adVertiserId               广告主账号ID
	 * @param advertisingProgrammeNameId 广告计划名称ID
	 * @return 验证结果
	 */
	public JsonResult T1002Validate(JSONObject jsonObject) {
		String phone = jsonObject.getString("phone");
		String phoneLocation = jsonObject.getString("phoneLocation");
		String sex = jsonObject.getString("sex");
		String age = jsonObject.getString("age");
		String career = jsonObject.getString("career");
		String guestTime = jsonObject.getString("guestTime");
		String media = jsonObject.getString("media");
		String mediaUrl = jsonObject.getString("mediaUrl");
		String advertisingPositionID = jsonObject.getString("advertisingPositionID");
		String landingPageURL = jsonObject.getString("landingPageURL");
		String stayTime = jsonObject.getString("stayTime");
		String message = jsonObject.getString("message");
		String adVertiserId = jsonObject.getString("adVertiserId");
		String advertisingProgrammeNameId = jsonObject.getString("advertisingProgrammeNameId");
		// 验证错误空信息
		StringBuilder errorValidateNullMsg = new StringBuilder();
		// 非空验证
		if (StringUtils.isBlank(phone)) {
			errorValidateNullMsg.append("<br/>手机号码");
		}
		if (StringUtils.isBlank(phoneLocation)) {
			errorValidateNullMsg.append("<br/>归属地");
		}
		if (StringUtils.isBlank(adVertiserId)) {
			errorValidateNullMsg.append("<br/>广告主账号ID");
		}
		if (StringUtils.isBlank(advertisingProgrammeNameId)) {
			errorValidateNullMsg.append("<br/>广告计划名称ID");
		}
		if (StringUtils.isBlank(media)) {
			errorValidateNullMsg.append("<br/>投放媒体");
		}
		if (StringUtils.isBlank(guestTime)) {
			errorValidateNullMsg.append("<br/>获客时间");
		}
		if (StringUtils.isBlank(stayTime)) {
			errorValidateNullMsg.append("<br/>停留时间（秒）");
		}
		if (errorValidateNullMsg.toString().length() > 0) {
			jsonResult = new JsonResult(JsonResultCodeEnum.ERROR_VALIDATE_NULL.getCode(),
					JsonResultCodeEnum.ERROR_VALIDATE_NULL.getMsg() + errorValidateNullMsg, null);
			return jsonResult;
		}
		// 格式验证
		// 验证格式错误信息
		StringBuilder errorIncorrectFormatMsg = new StringBuilder();
		if (!StringUtils.isBlank(sex)) {
			if ("男".equals(sex)) {
				sex = "1";
			} else if ("女".equals(sex)) {
				sex = "2";
			} else {
				errorIncorrectFormatMsg.append("<br/>性别参数格式错误,例:(男  女)");
			}
		}
		Integer ages = null;
		if (!StringUtils.isBlank(age)) {
			Pattern pattern = Pattern.compile("[0-9]*");
			if (!pattern.matcher(age).matches()) {
				errorIncorrectFormatMsg.append("<br/>年龄参数格式错误,例:(0)");
			} else {
				ages = Integer.valueOf(age);
			}
		}
		Date guestTimeDate = null;
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			guestTimeDate = sdf.parse(guestTime);
		} catch (ParseException e) {
			e.printStackTrace();
			errorIncorrectFormatMsg.append("<br/>获客时间字段,格式错误,例:(2019-05-13 12:00:00)");
		}
		Long stayTimes = null;
		if (!StringUtils.isBlank(stayTime)) {
			Pattern pattern = Pattern.compile("[0-9]*");
			if (!pattern.matcher(stayTime).matches()) {
				errorIncorrectFormatMsg.append("<br/>停留时间(秒)参数格式错误,例:(0)");
			} else {
				stayTimes = Long.valueOf(stayTime);
			}
		}
		if (errorIncorrectFormatMsg.toString().length() > 0) {
			jsonResult = new JsonResult(JsonResultCodeEnum.ERROR_INCORRECT_FORMAT.getCode(),
					JsonResultCodeEnum.ERROR_INCORRECT_FORMAT.getMsg() + errorIncorrectFormatMsg, null);
			return jsonResult;
		}
		// ID验证
		// 验证ID错误信息
		StringBuilder errorValidateIdMsg = new StringBuilder();
		if (adVertiserService.get(adVertiserId) != null) {
			// 验证广告计划名称是否属于此广告主
			Ad adWhere = new Ad();
			adWhere.setId(advertisingProgrammeNameId);
			adWhere.setVertiserId(adVertiserId);
			if (adService.findCount(adWhere) > 0) {
				Map<String, Object> map = new HashMap<String, Object>();
				// 封装参数
				AdGuest insert = new AdGuest();
				insert.setMobile(phone);
				insert.setMobileLocation(phoneLocation);
				insert.setSex(sex);
				insert.setAge(ages);
				insert.setCareer(career);
				insert.setGuestTime(guestTimeDate);
				insert.setComeFrom(media);
				insert.setMediaUrl(mediaUrl);
				insert.setMediaAdId(advertisingPositionID);
				insert.setToGroundUrl(landingPageURL);
				insert.setStopTime(stayTimes);
				insert.setMessage(message);
				insert.setAdVertiserId(adVertiserId);
				insert.setAdId(advertisingProgrammeNameId);
				map.put("insert", insert);
				jsonResult = new JsonResult(JsonResultCodeEnum.SUCCESS.getCode(), JsonResultCodeEnum.SUCCESS.getMsg(),
						map);
			} else {
				errorValidateIdMsg.append("<br/>广告计划名称ID错误,此广告主账号ID未存在此广告计划名称ID");
			}
		} else {
			errorValidateIdMsg.append("<br/>广告主账号ID错误");
		}
		if (errorValidateIdMsg.toString().length() > 0) {
			jsonResult = new JsonResult(JsonResultCodeEnum.ERROR_INCORRECT_FORMAT.getCode(),
					JsonResultCodeEnum.ERROR_INCORRECT_FORMAT.getMsg() + errorValidateIdMsg, null);
			return jsonResult;
		}
		return jsonResult;
	}

}